<?php

namespace App\Http\Controllers\Api;

use App\Model\User;
use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use Config;

class UserController extends Controller
{
    /**
     * @param Request $request
     * 通过code获取sessionKey,用户信息
     */
    public function getSessionKey(Request $request){
        $code = $request->input("code");
        $appid = Config::get('wechat.mini_program.default.app_id');
        $secret = Config::get('wechat.mini_program.default.secret');
        if(!$code || !$appid || !$secret){
            $this->error('非法请求'.__LINE__);
        }
        $url = 'https://api.weixin.qq.com/sns/jscode2session?appid='.$appid.'&secret='.$secret.'&js_code='.$code.'&grant_type=authorization_code';
        $res = $this->httpRequest($url);
        echo $res;
    }

    /**
     * @param Request $request
     * 授权登录获取用户信息接口
     */
    public function authLogin(Request $request){
        $data = $request->all();
        $user = new User();
        if(!$data['openid']){
            $this->error('授权失败'.__LINE__);
        }
        $userInfo = $user->where('openid',$data['openid'])->first();
        if(!$userInfo['openid']){
            $user = new User();
            $user->openid = $data['openid'];
            $user->sex = $data['gender'];
            $user->headurl = $data['headurl'];
            $user->username = $data['username'];
            $user->country = $data['country'];
            $user->province = $data['province'];
            $user->city = $data['city'];
            $res = $user->save();
            if($res){
                $info = array();
                $info['id'] = $user->id;
                $info['nickname'] = $data['username'];
                $info['avatarUrl'] = $data['headurl'];
                $this->success($info);
            }else{
                $this->error('授权失败'.__LINE__);
            }
        }else{
            $info = array();
            $info['id'] = $userInfo['id'];
            $info['nickname'] = $data['username'];
            $info['avatarUrl'] = $data['headurl'];
            $this->success($info);
        }
    }

    /**
     * @param $url
     * Curl请求
     */
    private function httpRequest($url){
        $ch = curl_init();
        curl_setopt($ch,CURLOPT_URL,$url);
        curl_setopt($ch,CURLOPT_HEADER,0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
        $res = curl_exec($ch);
        curl_close($ch);
        echo $res;
    }
}
